<?php

class LiteRegExp {

	/**
	 * @var string
	 */
	private $pattern;

	/**
	 * @var int
	 */
	private $count;

	/**
	 * @var array
	 */
	private $matches;

	/**
	 * @param $pattern
	 */
	function __construct($pattern = null){
		if(null !== $pattern) {
			$this->setPattern($pattern);
		}
	}

	/**
	 * Valida <code>$string</code> utilizando la expresion regular
	 * 
	 * @param string $string
	 * @param int $startFrom
	 * @return boolean
	 */
	function test($string, $startFrom = 0){
		return 0 !== $this->match($string, $startFrom);
	}

	/**
	 * Comprueba
	 * 
	 * @param string $string
	 * @param int $startFrom=0
	 * @return boolean
	 */
	function match($string, $startFrom = 0){
		$this->count = preg_match_all($this->pattern, $string, $this->matches, false, $startFrom);
		if(false === $this->count) {
			$this->count = 0;
		}
		return $this->count > 0;
	}

	/**
	 * Reemplaza <code>$string</code> con <code>$replacement</code> hasta <code>$limit</code> veces
	 * 
	 * @param string $string
	 * @param $replacement
	 * @param $limit
	 * @return LiteString
	 */
	function replace($string, $replacement, $limit = -1){
		LiteString::toString(preg_replace($this->pattern, $replacement, $string, $limit, $this->count));
	}

	/**
	 * Reemplaza en <code>$string</code>
	 * @param string $string
	 * @param $replacement
	 */
	function replaceFirst($string, $replacement){
		return $this->replace($string, $replacement, 1);
	}

	/**
	 * Realiza un reemplazo sobre el string utilizando una funcion de reemplazo
	 * 
	 * @param string $string
	 * @param LiteCallback $replaceFn
	 * @return LiteString
	 */
	function replaceWith($string, LiteCallable $replaceFn){
		return LiteString::toString(preg_replace_callback($this->pattern, $replaceFn->getCallback(), $string));
	}

	/**
	 * @return LiteString
	 */
	function getPattern(){
		return $this->pattern;
	}

	/**
	 * @param string $pattern
	 */
	function setPattern($pattern){
		return $this->pattern = LiteString::toString($pattern);
	}

	/**
	 * @return int $count
	 */
	function getCount(){
		return $this->count;
	}

	/**
	 * @return array $matches
	 */
	function getMatches(){
		return $this->matches;
	}
}
